import React, { ReactNode, useState } from "react";
import * as auth from "../api";
export interface User {
  userName: string;
  roleId: number;
  token: string;
  userId: number;
  email?: string
}

interface AuthForm {
  loginName: string;
  password: string;
}

const AuthContext = React.createContext<
  | {
      user: User | null;
      login: (form: AuthForm) => Promise<void>;
      logout: () => Promise<void>;
      setUser: React.Dispatch<React.SetStateAction<User | null>>
    }
  | undefined
>(undefined);
AuthContext.displayName = "AuthContext";

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const useValue = localStorage.getItem('userAuth') ? JSON.parse(localStorage.getItem('userAuth') as string): null
  const [user, setUser] = useState<User | null>(useValue);

  // point free
  const login = (form: AuthForm) => auth.login(form).then((res: any)  => {
    localStorage.setItem('userAuth', JSON.stringify(res))
    // 获取用户的详细信息
    auth.getUserInfo().then((info: any) => {
      localStorage.setItem('userAuth', JSON.stringify({
        ...res,
        ...info.userInfoModel,
        token: res.token
      }))
      setUser({
        ...res,
        ...info.userInfoModel,
        token: res.token
      })
    })
    
  });
  const logout = () => auth.logout().then(() => setUser(null));

  return (
    <AuthContext.Provider
      children={children}
      value={{ user, login, logout, setUser }}
    />
  );
};

export const useAuth = () => {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth必须在AuthProvider中使用");
  }
  return context;
};
